# -*- coding=utf8 -*-
import logging
import math
import requests
import time
import threading
import json
from lxml import etree
from items import PospalMemberItem
from items import PospalMemberTaskItem
from pospal import pipelines
from mysqlmgr import mysqlmgr
from youzan import member_spider as youzan


createUserId = '2968559'
username = '13810807631'
password = '888008'
# 导入时间间隔 1小时， 60*60*3
import_interval_time = 60*60*3
# 30分钟
session_refresh_time = 60*30
#设置头信息
headers_base = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2',
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36',
    'Referer': 'http://www.zhihu.com/',
}
session = requests.session()

# 公共方法
def post(url, data=None, verify=False):
   return session.post(url=url, headers=headers_base, data=data, verify=verify)

# 公共方法
def get(url, data=None, verify=False):
   return session.get(url=url, headers=headers_base, data=data, verify=verify)

# 登录
def login():
    formdata = {
        'userName': username,
        'password': password
    }
    url = 'https://user.pospal.cn/account/signin'
    # 使用seesion登录，这样的好处是可以在接下来的访问中可以保留登录信息
    response = post(url=url, data=formdata, verify=True)
    json_data = response.json()
    # 判断successed=true, 则继续执行，否则发送错误邮件给 xlpc_bj@163.com
    if json_data['successed'] is False:
        logging.error('after_login failed')
        return False
    else:
        return True

def sync_members(loop=True):
    # 时间范围8:00 -- 22:00 内执行
    hour = time.strftime('%H', time.localtime(time.time()))
    if int(hour) in range(8, 24):
    # if int(hour) in range(0, 25):

        formdata = {
            'createUserId': createUserId,
            'categoryUid': '',
            'tagUid': '',
            'type': '1',
            'keyword': ''
        }
        url = 'http://beta7.pospal.cn/Customer/LoadCustomerSummary'
        response = session.post(url=url, data=formdata)
        json_data = response.json()
        if json_data['successed'] is False:
            logging.error('parse_customer_summary failed')
            return
        # 记录总数
        total_record = int(json_data['totalRecord'])
        # 每页50
        page_size = 50
        # 计算总页数
        page_total = math.ceil(total_record / page_size)  # 向上取整
        # range(1, 5), 1,2,3,4
        for page_index in range(1, page_total + 1):
            post_load_customers_by_page(page_index, page_size)
    #TODO 自动同步
    #deal_task()

    if loop is True:
        # 定时循环调用
        timer = threading.Timer(import_interval_time, sync_members, [True])
        timer.start()

# 会员列表页面
def post_load_customers_by_page(page_index=1, page_size=50):
    formdata = {
        'createUserId': createUserId,
        'categoryUid': '',
        'tagUid': '',
        'type': str(1),
        'keyword': '',
        'pageIndex': str(page_index),
        'pageSize': str(page_size),
        'orderColumn': '',
        'asc': 'false'
    }

    url = 'http://beta7.pospal.cn/Customer/LoadCustomersByPage'
    response = post(url=url, data=formdata)
    json_data = response.json()
    if json_data['successed'] is False:
        logging.error('parse_customer_summary failed')
        return
    content = json_data['contentView']
    html = etree.HTML(content)
    trs = html.xpath('//tbody/tr')  # tbody/trs

    cur_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    for tr in trs:
        item = PospalMemberItem()
        item['member_number'] = tr.xpath('td[3]/text()')[0]
        item['real_name'] = tr.xpath('td[4]/text()')[0]
        item['mobile'] = tr.xpath('td[5]/text()')[0]
        item['member_point'] = int(float(tr.xpath('td[8]/text()')[0]))
        item['is_enabled'] = '1'
        item['is_dealed'] = '0'
        item['create_time'] = cur_datetime
        item['modify_time'] = cur_datetime
        pipelines.process_item(item)

def deal_task():
    add_member_tasks, change_point_tasks = get_deal_task()
    deal_add_member_task(add_member_tasks)
    deal_change_point_task(change_point_tasks)


def deal_add_member_task(pospal_member_task_items):
    # 调用有赞接口，创建会员,PospalMemberItem
    for item in pospal_member_task_items:
        youzan.add_my_member(item)


def deal_change_point_task(pospal_member_task_items):
    # 调用有赞接口，增加积分,PospalMemberItem
    for item in pospal_member_task_items:
        youzan.change_my_point(item)


def get_deal_task():
    '''
    :return:  [PospalMemberItem],[PospalMemberTaskItem]
    '''
    add_member_tasks = []
    change_point_tasks = []
    with mysqlmgr.mysql() as cursor:
        select_sql = 'select id, member_number, real_name, mobile, old_point, new_point, change_point,task_type, create_time,modify_time' \
                     ' from pospal_member_task where is_dealed=0'
        cursor.execute(select_sql)
        results = cursor.fetchall()
        for row in results:
            # 1:add_member,2:add_point
            if row['task_type'] == 1 :
                item = PospalMemberTaskItem()
                item['id'] = row['id']
                item['member_number'] = row['member_number']
                item['real_name'] = row['real_name']
                item['mobile'] = row['mobile']
                item['new_point'] = row['new_point']
                item['old_point'] = row['old_point']
                item['change_point'] = row['change_point']
                item['create_time'] = row['create_time']
                item['modify_time'] = row['modify_time']
                add_member_tasks.append(item)
            elif row['task_type'] == 2 :
                item = PospalMemberTaskItem()
                item['member_number'] = row['member_number']
                item['real_name'] = row['real_name']
                item['mobile'] = row['mobile']
                item['new_point'] = row['new_point']
                item['old_point'] = row['old_point']
                item['change_point'] = row['change_point']
                item['create_time'] = row['create_time']
                item['modify_time'] = row['modify_time']
                change_point_tasks.append(item)
        return add_member_tasks, change_point_tasks


def add_my_member(youzan_member_task_item):
    '''
    :param item: YouzanMemberTaskItem
    '''
    create_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    customer_json = {
        'id': 0,
        'enable': '1',
        'number': youzan_member_task_item['mobile'],
        'name': youzan_member_task_item['real_name'],
        'customerCategoryUid': '0',
        'categoryName': '无',
        'discount': '100',
        'money': '0',
        'point': youzan_member_task_item['new_point'],
        'tel': youzan_member_task_item['mobile'],
        'password': '',
        'birthday': '',
        'createdDate': create_time,
        'expiryDate': '',
        'credit': '0',
        'qq': '',
        'email': '',
        'address': '',
        'remarks': 'from youzan'
    }
    # api
    formdata = {
        'customerJson': json.dumps(customer_json),
        'originalMoney': '0',
        'originalPoint': '0'
    }
    response = post(url='http://beta7.pospal.cn/Customer/SaveCustomer', data=formdata)
    json_data = response.json()
    #{"successed":false,"msg":"新会员的编号已被使用过，请重新填写"}
    if json_data['successed'] is False:
        logging.error('add my member failed')
        logging.error(youzan_member_task_item)
         # return 忽略错误

    logging.info('=========add pospal member successfully=========')
    logging.info(youzan_member_task_item)

    item = PospalMemberItem()
    item['member_number'] = youzan_member_task_item['mobile'] #******
    item['mobile'] = youzan_member_task_item['mobile']
    item['real_name'] = youzan_member_task_item['real_name']
    item['member_point'] = youzan_member_task_item['new_point']
    item['create_time'] = youzan_member_task_item['create_time']
    item['modify_time'] = youzan_member_task_item['modify_time']

    # 数据库
    with mysqlmgr.mysql() as cursor:
        insert_history_sql = 'insert into pospal_member_history(member_number, real_name, mobile, member_point, is_enabled, is_dealed, create_time, modify_time)values(%s, %s, %s, %s, %s, %s, %s, %s)'
        params = (
            item['member_number'], item['real_name'], item['mobile'], item['member_point'], 1, 0,
            item['create_time'], item['modify_time'])
        cursor.execute(insert_history_sql, params)

        # is_deal=1
        udpate_task_sql = 'update youzan_member_task set is_dealed=1 where id=%s'
        params = youzan_member_task_item['id']
        cursor.execute(udpate_task_sql, params)


def change_my_point(youzan_member_task_item):
    '''
    :param item: PospalMemberTaskItem
    '''
    # PospalMemberItem
    item = pipelines.get_from_history_by_mobile(youzan_member_task_item['mobile'])
    if item is None:
        return
    #获得旧数据
    formdata = {
        'number': str(item['member_number']),
    }
    response = post(url='http://beta7.pospal.cn/Customer/FindCustomer', data=formdata)
    json_data = response.json()
    if json_data['successed'] is False:
        logging.error('FindCustomer failed')
        logging.error(youzan_member_task_item)
        return

    # 增加积分
    json_data = json_data['customer']
    member_point = int(json_data['point']) + int(youzan_member_task_item['change_point'])
    customer_json = {
        'id': json_data['id'],
        'enable': json_data['enable'],
        'number': json_data['number'],
        'name': json_data['name'],
        'customerCategoryUid': json_data['customerCategoryUid'],
        'categoryName': '无',
        'discount': json_data['discount'],
        'money': json_data['money'],
        'point': member_point,
        'tel': json_data['tel'],
        'password': json_data['password'],
        'birthday': json_data['birthday'],
        'createdDate': json_data['createdDate'],
        'expiryDate': '',
        'credit':json_data['credit'],
        'qq': json_data['qq'],
        'email': json_data['email'],
        'address': json_data['address'],
        'remarks': json_data['remarks'],
    }
    # api
    formdata = {
        'customerJson': json.dumps(customer_json),
        'originalMoney': '0',
        'originalPoint': '0'
    }
    response = post(url='http://beta7.pospal.cn/Customer/SaveCustomer', data=formdata)
    json_data = response.json()
    #{'successed': False, 'msg': '在您操作过程中，会员积分在收银端已发生了变动，请确认!'}
    if json_data['successed'] is False:
        logging.error('change point failed')
        logging.error(youzan_member_task_item)
        return
    logging.info('=========change pospal point sucessfully=========')
    logging.info(youzan_member_task_item)
    # 数据库
    with mysqlmgr.mysql() as cursor:
        insert_history_sql = 'insert into youzan_member_history(member_number, real_name, mobile, member_point, is_enabled, is_dealed, create_time, modify_time)values(%s, %s, %s, %s, %s, %s, %s, %s)'
        params = (
            item['member_number'], item['real_name'], item['mobile'], member_point, 1, 0,
            item['create_time'], item['modify_time'])
        cursor.execute(insert_history_sql, params)
        # is_deal=1
        udpate_task_sql = 'update pospal_member_task set is_dealed=1 where id=%s'
        params = youzan_member_task_item['id']
        cursor.execute(udpate_task_sql, params)


# 保持session
def keep_session(loop=True):
    logging.info('keep session ... ...')
    url = 'http://beta7.pospal.cn/Dashboard'
    response = get(url=url)
    if response.status_code != 200:#TODO 不是这么判断的
        logging.error('keep session failed')
        # 重新登录
        return login()
    logging.info('keep session successfully')
    #
    if loop is True:
        timer = threading.Timer(session_refresh_time, keep_session, [True])
        timer.start()


def exec_one():
    login_result = login()
    if login_result is False:
        print('error login failed')
        return

    # 1.导入用户数据
    sync_members(loop=False)

if __name__=='__main__':
    exec_one()
    # deal_task()
